package com.hfjyz.payment.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hfjyz.payment.bean.cms.RdType;

public class DBAccessor {
    private static final String SELECT_SQL = "select id, orderState from orderInfo where id=?";
    private static final String UPDATE_SQL = "update orderInfo set orderState=1 where id=?";
    private static final Log DEBUG_LOG = LogFactory.getLog("payment.debugLog");

    public static Connection getConnection(String driver, String jdbcUrl, String user, String password)
            throws Exception {
        Class.forName(driver);
        Connection con = DriverManager.getConnection(jdbcUrl, user, password);
        return con;
    }

    public static void checkOrderState(Connection conn, RdType rd) throws Exception {
        Integer orderState = getOrderState(conn, rd.getOrderNum());
        DEBUG_LOG.debug("orderNum=" + rd.getOrderNum() + ";orderState" + orderState);
        if (orderState != null && orderState.intValue() == 0) {
            updateOrderState(conn, rd.getOrderNum());
            DEBUG_LOG.debug("update orderState success. orderNum=" + rd.getOrderNum());
        }
    }

    private static Integer getOrderState(Connection conn, String orderNum) throws SQLException {
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(SELECT_SQL);
            pst.setString(1, orderNum);
            ResultSet rt = pst.executeQuery();

            if (rt.next()) {
                return rt.getInt("orderState");
            }
            return null;
        } finally {
            pst.close();
        }
    }

    private static void updateOrderState(Connection conn, String orderNum) throws SQLException {
        PreparedStatement pst = null;
        try {
            pst = conn.prepareStatement(UPDATE_SQL);
            pst.setString(1, orderNum);
            pst.executeUpdate();
        } finally {
            pst.close();
        }
    }
}
